package com.tansun.easycare.rule.policytree.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.tansun.easycare.core.utils.IdGen;
import com.tansun.easycare.rule.common.Constant;
import com.tansun.easycare.rule.common.rulebasebean.Action;
import com.tansun.easycare.rule.common.rulebasebean.DThen;
import com.tansun.easycare.rule.common.rulebasebean.DWhen;
import com.tansun.easycare.rule.common.rulebasebean.Fact;
import com.tansun.easycare.rule.common.rulebasebean.RuleCollection;
import com.tansun.easycare.rule.common.rulebasebean.RuleItem;
import com.tansun.easycare.rule.common.service.impl.RuleBaseServiceImpl;
import com.tansun.easycare.rule.decisiontree.dao.RuleTreeNodeDao;
import com.tansun.easycare.rule.decisiontree.entity.RuleTreeConditions;
import com.tansun.easycare.rule.decisiontree.entity.RuleTreeNode;
import com.tansun.easycare.rule.decisiontree.entity.RuleTreeParam;
import com.tansun.easycare.rule.decisiontree.entity.RuleTreeScene;
import com.tansun.easycare.rule.decisiontree.service.DecisionTreeService;
import com.tansun.easycare.rule.decisiontree.service.RuleTreeConditionsService;
import com.tansun.easycare.rule.decisiontree.service.RuleTreeParamService;
import com.tansun.easycare.rule.exception.BizException;
import com.tansun.easycare.rule.policytree.model.PolicyTreeItem;
import com.tansun.easycare.rule.policytree.model.PolicyTreeKey;
import com.tansun.easycare.rule.policytree.model.PolicyTreeModel;
import com.tansun.easycare.rule.policytree.model.PolicyTreeScene;
import com.tansun.easycare.rule.policytree.model.PolicyTreeVO;
import com.tansun.easycare.rule.policytree.service.PolicyTreeHtml;
import com.tansun.easycare.rule.policytree.service.PolicyTreeService;
import com.tansun.easycare.rule.policytree.service.RuleTreeSceneService;
import com.tansun.easycare.rule.referencedata.entity.RuleReferenceData;
import com.tansun.easycare.rule.referencedata.service.RuleReferenceDataService;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.rulemange.model.RuleManageVO;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.easycare.rule.ruleversion.entity.RuleVersioninfo;
import com.tansun.easycare.rule.ruleversion.service.RuleVersioninfoService;
import com.tansun.easycare.rule.utils.DroolsUtils;
import com.tansun.rule.common.RuleModelTypeEnum;

@Service
public class PolicyTreeServiceImpl extends RuleBaseServiceImpl<RuleTreeNodeDao, RuleTreeNode> implements PolicyTreeService {
    @Autowired
    private RuleManageService ruleManageService;
    @Autowired
    private RuleTreeConditionsService ruleTreeConditionsService;
    @Autowired
    private RuleTreeParamService ruleTreeParamService;
    @Autowired
    private RuleTreeSceneService ruleTreeSceneService;
    @Autowired
    private RuleVersioninfoService ruleVersioninfoService;

    @Autowired
    private RuleReferenceDataService ruleReferenceDataService;
    @Autowired
    private DecisionTreeService decisionTreeService;


    @Override
    public PolicyTreeModel findPolicyTreeModel(String code, String version, String projectCode) throws BizException {
        PolicyTreeModel policyTreeModel = new PolicyTreeModel();
        RuleManage ruleManageInfo = new RuleManage();
        ruleManageInfo.setCode(code);
        ruleManageInfo.setVersion(version);
        ruleManageInfo.setModelType(RuleModelTypeEnum.PolicyTree.code);
        ruleManageInfo.setProjectCode(projectCode);
        List<RuleManage> list = this.ruleManageService.findList(ruleManageInfo);
        if (list == null || list.size() == 0) {
            throw new BizException("");
        }
        RuleManage ruleManage = list.get(0);
        policyTreeModel.setPolicyTreeModel(ruleManage);

        //查找TreeNode
        RuleTreeNode treeNode = new RuleTreeNode();
        treeNode.setManageId(ruleManage.getId());
        treeNode.setVersion(ruleManage.getVersion());
        List<RuleTreeNode> nodes = this.findList(treeNode);

        PolicyTreeItem policyTreeItem = null;
        RuleTreeConditions treeConditionsInfo = null;
        PolicyTreeScene policyTreeScene = null;

        RuleTreeConditions ruleTreeConditions = null;
        for (RuleTreeNode ruleTreeNode : nodes) {
            policyTreeItem = new PolicyTreeItem();

            try {
                BeanUtils.copyProperties(policyTreeItem, ruleTreeNode);
            } catch (Exception e) {
                throw new BizException("E-000000");
            }
            policyTreeItem.setId(ruleTreeNode.getNodeId());
            policyTreeItem.setName(ruleTreeNode.getNodeName());

            if (ruleTreeNode.getPid() == null) {
                policyTreeItem.setFloorNum(ruleTreeNode.getTotalFloor());
            }

            //policyTreeItem.setRuleTreeNode(ruleTreeNode);
            treeConditionsInfo = new RuleTreeConditions();
            treeConditionsInfo.setNodeId(ruleTreeNode.getNodeId());
            treeConditionsInfo.setVersion(ruleManage.getVersion());
            treeConditionsInfo.setManageId(ruleManage.getId());

            List<RuleTreeConditions> cList = ruleTreeConditionsService.findList(treeConditionsInfo);
            if (cList != null && cList.size() > 0) {
                ruleTreeConditions = cList.get(0);
                try {
                    BeanUtils.copyProperties(policyTreeItem, ruleTreeConditions);
                } catch (Exception e) {
                    throw new BizException("E-000000");
                }
                policyTreeItem.setId(ruleTreeNode.getNodeId());
                policyTreeItem.setKeyId(ruleTreeConditions.getKeyId());
                policyTreeItem.setSymbol(ruleTreeConditions.getSymbol());
                policyTreeItem.setPosition(ruleTreeConditions.getPosition());
                if (ruleTreeConditions.getControlValue() != null) {
                    policyTreeItem.setLeftOpt(ruleTreeConditions.getLeftOpt());
                    policyTreeItem.setControlValue(ruleTreeConditions.getControlValue());
                    policyTreeItem.setRightOpt(ruleTreeConditions.getRightOpt());
                }


            }
            //构建树节点
            policyTreeModel.getPolicyTreeItem().add(policyTreeItem);
            //动作场景
            PolicyTreeScene childTreeScene = null;
            if ("true".equals(ruleTreeNode.getIsLeaf())) {


                RuleTreeScene treeScene = this.ruleTreeSceneService.get(ruleTreeNode.getActionSceneId());
                if (treeScene == null) {
                    throw new BizException("E-000600");
                }
                policyTreeScene = new PolicyTreeScene();
                try {
                    BeanUtils.copyProperties(policyTreeScene, treeScene);
                } catch (Exception e) {
                    throw new BizException("E-000000");
                }
                policyTreeScene.setName(treeScene.getNameen());
                policyTreeScene.setLabel(treeScene.getNamecn());


                RuleTreeScene sceneInfo = new RuleTreeScene();
                sceneInfo.setParentId(treeScene.getNodeId());
                sceneInfo.setManageId(ruleManage.getId());
                List<RuleTreeScene> sList = this.ruleTreeSceneService.findList(sceneInfo);
                for (RuleTreeScene chTreeScene : sList) {
                    childTreeScene = new PolicyTreeScene();
                    try {
                        BeanUtils.copyProperties(childTreeScene, chTreeScene);
                    } catch (Exception e) {
                        throw new BizException("E-000000");
                    }
                    childTreeScene.setName(chTreeScene.getNameen());
                    childTreeScene.setLabel(chTreeScene.getNamecn());

                    policyTreeScene.getOutputVariables().add(childTreeScene);
                }
                policyTreeModel.getActionScene().add(policyTreeScene);
            }


        }
        //决策键
        RuleTreeParam treeParam = new RuleTreeParam();
        treeParam.setManageId(ruleManage.getId());
        treeParam.setVersion(ruleManage.getVersion());
        List<RuleTreeParam> params = ruleTreeParamService.findList(treeParam);
        PolicyTreeKey policyTreeKey = null;
        for (RuleTreeParam param : params) {
            policyTreeKey = new PolicyTreeKey();
            try {
                BeanUtils.copyProperties(policyTreeKey, param);
                policyTreeKey.setName(param.getNamecn());
                policyTreeKey.setValue(param.getNameen());
            } catch (Exception e) {
                throw new BizException("E-000000");
            }
            policyTreeModel.getPolicyTreeKey().add(policyTreeKey);
        }
        return policyTreeModel;
    }

    @Override
    public void saveOrUpdate(PolicyTreeModel treeEntity) throws BizException {

        RuleManage ruleManage = treeEntity.getPolicyTreeModel();
        ruleManage.setModelType(RuleModelTypeEnum.PolicyTree.code);
        if ("true".equals(ruleManage.getIsTemp())) {
            ruleManage.setStatus(Constant.RULE_STATUS_TEMP);// 暂存
        } else {
            ruleManage.setIsTemp("false");
            ruleManage.setStatus(Constant.RULE_STATUS_NORMAL);// 保存
        }
        this.ruleManageService.saveOrUpdate(ruleManage);
        //关键字

        List<PolicyTreeKey> keys = treeEntity.getPolicyTreeKey();
        RuleTreeParam ruleTreeParam = null;
        List<RuleTreeParam> params = new ArrayList();
        Map<String, RuleTreeParam> keyMap = new HashMap();

        //引用数据
        Map<String, RuleReferenceData> refMap = new HashMap();
        String strkey = null;
        for (PolicyTreeKey key : keys) {
            ruleTreeParam = new RuleTreeParam();
            try {
                BeanUtils.copyProperties(ruleTreeParam, key);
            } catch (Exception e) {
                throw new BizException(e, "E-000000");
            }
            ruleTreeParam.setId(IdGen.uuid());
            ruleTreeParam.setNamecn(key.getName());
            ruleTreeParam.setNameen(key.getValue());
            ruleTreeParam.setProjectCode(ruleManage.getProjectCode());
            ruleTreeParam.setVersion(ruleManage.getVersion());
            ruleTreeParam.setManageId(ruleManage.getId());
            keyMap.put(key.getId(), ruleTreeParam);
            params.add(ruleTreeParam);
            strkey = ruleTreeParam.getClassName() + "|" + ruleTreeParam.getNameen() + "|in";
            this.ruleReferenceDataService.collectCommonData(ruleTreeParam, strkey, "in", ruleManage, refMap);
        }
        this.ruleTreeParamService.insertBatch(params, true);


        //场景
        List<PolicyTreeScene> scenes = treeEntity.getActionScene();
        RuleTreeScene ruleTreeScene = null;
        List<PolicyTreeScene> childScenes = null;
        RuleTreeScene cTreeScene = null;
        List<RuleTreeScene> inTreeScenes = new ArrayList();
        Map<String, RuleTreeScene> map = new HashMap();
        for (PolicyTreeScene treeScene : scenes) {
            ruleTreeScene = new RuleTreeScene();
            try {
                BeanUtils.copyProperties(ruleTreeScene, treeScene);
                ruleTreeScene.setSceneCode(treeScene.getDefaultActionId());
                ruleTreeScene.setNamecn(treeScene.getLabel());
                ruleTreeScene.setNameen(treeScene.getName());
                ruleTreeScene.setProjectCode(ruleManage.getProjectCode());
                ruleTreeScene.setVersion(ruleManage.getVersion());
                ruleTreeScene.setManageId(ruleManage.getId());
                ruleTreeScene.setId(IdGen.uuid());
                ruleTreeScene.setNodeId(IdGen.uuid());
                inTreeScenes.add(ruleTreeScene);
                //收集引用数据
                strkey = ruleTreeScene.getClassName() + "|" + ruleTreeScene.getNameen() + "|out";
                this.ruleReferenceDataService.collectCommonData(ruleTreeScene, strkey, "out", ruleManage, refMap);
                //
                map.put(treeScene.getId(), ruleTreeScene);
                childScenes = treeScene.getOutputVariables();
                if (childScenes != null) {
                    for (PolicyTreeScene scene : childScenes) {
                        cTreeScene = new RuleTreeScene();
                        BeanUtils.copyProperties(cTreeScene, scene);
                        cTreeScene.setNamecn(scene.getLabel());
                        cTreeScene.setNameen(scene.getName());
                        cTreeScene.setId(IdGen.uuid());
                        cTreeScene.setManageId(ruleManage.getId());
                        cTreeScene.setParentId(ruleTreeScene.getNodeId());
                        cTreeScene.setProjectCode(ruleManage.getProjectCode());
                        cTreeScene.setVersion(ruleManage.getVersion());
                        inTreeScenes.add(cTreeScene);
                        //收集数据
                        strkey = cTreeScene.getClassName() + "|" + cTreeScene.getNameen() + "|out";
                        this.ruleReferenceDataService.collectCommonData(cTreeScene, strkey, "out", ruleManage, refMap);
                    }
                }

            } catch (Exception e) {
                throw new BizException(e, "E-000000");
            }

        }
        //保存收集引用数据
        this.ruleReferenceDataService.saveReferenceData(refMap);

        this.ruleTreeSceneService.insertBatch(inTreeScenes, true);

        List<PolicyTreeItem> items = treeEntity.getPolicyTreeItem(); // 节点信息

        RuleTreeNode ruleTreeNode = null;
        List<RuleTreeNode> inTreeNodes = new ArrayList();
        //
        RuleTreeConditions ruleTreeConditions = null;
        List<RuleTreeConditions> inTreeConds = new ArrayList();

        int m = 0;
        for (PolicyTreeItem item : items) {
            ruleTreeNode = new RuleTreeNode();
            try {
                BeanUtils.copyProperties(ruleTreeNode, item);
            } catch (Exception e) {
                throw new BizException(e, "E-000000");
            }
            ruleTreeNode.setNodeId(item.getId());
            ruleTreeNode.setId(IdGen.uuid());
            ruleTreeNode.setVersion(ruleManage.getVersion());
            ruleTreeNode.setManageId(ruleManage.getId());
            ruleTreeNode.setNodeName(item.getName());
            ruleTreeNode.setProjectCode(ruleManage.getProjectCode());

            RuleTreeScene tmpScene = map.get(item.getActionSceneId());
            if (tmpScene != null)
                ruleTreeNode.setActionSceneId(tmpScene.getId());
            if (item.getPid() == null) {
                ruleTreeNode.setTotalFloor(item.getFloorNum());
            }
            inTreeNodes.add(ruleTreeNode);
            if (!"true".equals(item.getIsLeaf()) && item.getPid() != null) {
                ruleTreeConditions = new RuleTreeConditions();
                try {
                    BeanUtils.copyProperties(ruleTreeConditions, item);
                } catch (Exception e) {
                    throw new BizException(e, "E-000000");
                }
                RuleTreeParam keyParam = keyMap.get(item.getKeyId());
                if (keyParam != null) {
                    ruleTreeConditions.setKeyId(keyParam.getId());
                }
                ruleTreeConditions.setId(IdGen.uuid());
                ruleTreeConditions.setNodeId(ruleTreeNode.getNodeId());
                ruleTreeConditions.setManageId(ruleManage.getId());
                ruleTreeConditions.setProjectCode(ruleManage.getProjectCode());
                ruleTreeConditions.setVersion(ruleManage.getVersion());
                ruleTreeConditions.setSeq(m);
                m++;
                inTreeConds.add(ruleTreeConditions);
            }
        }
        this.insertBatch(inTreeNodes, true);
        this.ruleTreeConditionsService.insertBatch(inTreeConds, true);


        if ("false".equals(ruleManage.getIsTemp())) {
            String content;
            try {
                content = this.writeDrl(ruleManage, treeEntity.getPolicyTreeKey(), treeEntity.getPolicyTreeItem(), treeEntity.getActionScene());
                RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
                ruleVersioninfo.init(ruleManage, content);
                this.ruleVersioninfoService.save(ruleVersioninfo);
            } catch (Exception e) {
                throw new BizException(e, "E-000100");

            }

        }

    }

    @Override
    public PolicyTreeVO getTreeInfo(String treeId, String version) throws BizException {

        PolicyTreeVO policyTreeVO = new PolicyTreeVO();
        Map<String, Object> map = new HashMap();
        map.put("id", treeId);
        List<RuleManageVO> list = this.ruleManageService.findRuleManageVO(map);
        if (list == null || list.size() == 0) {
            throw new BizException("E-000600");
        }
        RuleManageVO tree = list.get(0);
        policyTreeVO.setTree(tree);

        if (StringUtils.isEmpty(version)) {
            version = tree.getVersion();
        }

        PolicyTreeModel treeModel = this.findPolicyTreeModel(tree.getCode(), version, tree.getProjectCode());

        policyTreeVO.setTreeHtml(new PolicyTreeHtml(treeModel).getHtml());
        policyTreeVO.setVersion(version);
        policyTreeVO.setTree(tree);
        policyTreeVO.setOptionHtml(getOptionHtml(tree.getId(), tree.getProjectCode(), version));
        if (treeModel.getActionScene() != null) {
            String json = JSON.toJSONString(treeModel.getActionScene()).replace(" ", "");
            json = StringEscapeUtils.escapeXml11(json);
            policyTreeVO.setActionDatas(json);
        }

        return policyTreeVO;

    }

    /**
     * 获取决策树的所有版本,并且生成option代码
     *
     * @param code        树形编码
     * @param projectCode 项目编码
     * @param version     版本号
     * @return 策略树option内容
     */
    private String getOptionHtml(String manageId, String projectCode, String version) {

        RuleVersioninfo versioninfo = new RuleVersioninfo();
        versioninfo.setManageId(manageId);
        versioninfo.setProjectCode(projectCode);
        List<RuleVersioninfo> list = this.ruleVersioninfoService.findList(versioninfo);

        StringBuffer options = new StringBuffer();
        if (list != null) {
            for (RuleVersioninfo ruleVersioninfo : list) {
                if (ruleVersioninfo.getVersion().lastIndexOf("tmp") > -1) continue;
                if (version.equals(ruleVersioninfo.getVersion())) {
                    options.append("<option selected >" + ruleVersioninfo.getVersion() + "</option>");
                } else {
                    options.append("<option>" + ruleVersioninfo.getVersion() + "</option>");
                }
            }
        }
        return options.toString();
    }

    /**
     * 保存Drool文件
     *
     * @param tree   策略树主体信息
     * @param keys   决策键
     * @param items  策略树节点
     * @param scenes 动作场景
     * @exception Exception 异常
     */
    private String writeDrl(RuleManage tree, List<PolicyTreeKey> keys, List<PolicyTreeItem> items, List<PolicyTreeScene> scenes) throws Exception {
//		if (keys == null) {
//			keys = readByOwnPath(PolicyTreeKey.class, tree.getProjectCode(),tree.getCode(),tree.getVersion());
//		}
//		if (items == null) {
//			items = readByOwnPath(PolicyTreeItem.class, tree.getProjectCode(),tree.getCode(),tree.getVersion());
//		}
//		if (scenes == null) {
//			scenes = readByOwnPath(PolicyTreeScene.class, tree.getProjectCode(),tree.getCode(),tree.getVersion());
//		}

        // 获取叶子节点
        List<PolicyTreeItem> leafItems = new ArrayList<PolicyTreeItem>();
        Map<String, PolicyTreeItem> branchMap = new HashMap<String, PolicyTreeItem>();// 分支Map<id,Object>
        for (PolicyTreeItem item : items) {
            if ("true".equals(item.getIsLeaf())) {
                leafItems.add(item);
            } else {
                if ("ROOT_V".equals(item.getId())) {
                    continue;
                }
                branchMap.put(item.getId(), item);
            }
        }
        if (leafItems.size() == 0 || keys.size() == 0 || scenes.size() == 0) {
            return "";
        }
        // 决策键Map<id,Key Object>
        Map<String, PolicyTreeKey> keyMap = new HashMap<String, PolicyTreeKey>();
        for (PolicyTreeKey key : keys) {
            keyMap.put(key.getId(), key);
        }

        // 动作场景输出变量
        Map<String, PolicyTreeScene> sceneMap = new HashMap<String, PolicyTreeScene>();
        for (PolicyTreeScene scene : scenes) {
//			sceneMap.put(scene.getId(), scene.getOutputVariables());
            sceneMap.put(scene.getId(), scene);
        }

        RuleCollection ruleCollection = new RuleCollection();
        ruleCollection.setDrlName(tree.getCode());
        ruleCollection.setObjName(tree.getName());
        ruleCollection.setContentType(RuleCollection.POLICYTREE);
        ruleCollection.setVersion(tree.getVersion());
        // 生成动作组
        int priority = 1;
        for (PolicyTreeItem leafItem : leafItems) {
            String ruleName = "policytree_";
            List<String> ruleNameExtList = new ArrayList<String>();
            String whenStr = generateDrl(branchMap.get(leafItem.getPid()), branchMap, keyMap, ruleNameExtList);
            String thenStr = "";
            // 加入动作场景输入变量
            PolicyTreeScene tempScene = sceneMap.get(leafItem.getActionSceneId());
            thenStr += "ruleHelper.setValue" + "($insertMap,\"" + tempScene.getClassName() + "." + tempScene.getName() + "\",\"" + tempScene.getControlValue() + "\");\n";
            // 获取动作场景输出列表
            for (PolicyTreeScene scene : tempScene.getOutputVariables()) {
                String methodStr = "ruleHelper.setValue";
                thenStr += methodStr + "($insertMap,\"" + scene.getClassName() + "." + scene.getName() + "\",\"" + scene.getControlValue() + "\");\n";
            }
            thenStr += "//leafNo:" + leafItem.getName();


            for (String rn : ruleNameExtList) {
                ruleName = ruleName + rn + "|";
            }
            RuleItem ruleItem = getCustomRule(ruleName, priority, whenStr, thenStr);
            ruleCollection.getListItem().add(ruleItem);
            priority--;
        }
        return DroolsUtils.convert2Drl(ruleCollection);
    }

    /**
     * 生成drl文件
     *
     * @param parentItem      树形父节点对象
     * @param itemMap         树形map {treeid:treeItem}
     * @param keyMap          决策键map {keyid:treeKey}
     * @param ruleNameExtList 规则名称列表
     * @return 参数值
     */
    private String generateDrl(PolicyTreeItem parentItem, Map<String, PolicyTreeItem> itemMap,
                               Map<String, PolicyTreeKey> keyMap, List<String> ruleNameExtList) {
        if (parentItem == null)
            return "";
        String retStr = "";
        PolicyTreeKey key = keyMap.get(parentItem.getKeyId());// 通过KeyId获取决策键数据
        retStr += " this[\"" + key.getClassName() + "\"][\"" + key.getValue() + "\"]";
        if (!StringUtils.isEmpty(parentItem.getPosition())) {
            retStr += ".get(" + parentItem.getPosition() + ")";
        }

        if (key.getDataType().equals("String")) {
            String symbol = "==";
            if (StringUtils.isEmpty(key.getDomain())) {
                if (parentItem.getSymbol().equals("startsWith") || parentItem.getSymbol().equals("endsWith")) {
                    retStr += "." + parentItem.getSymbol() + "(\"" + parentItem.getControlValue() + "\")";
                } else {
                    retStr += parentItem.getSymbol() + "\"" + parentItem.getControlValue() + "\"";
                }
            } else {
                symbol = parentItem.getSymbol().equals("0") ? " not in " : " in ";
                String result = parentItem.getControlValue();
//				for(String str:parentItem.getControlValues()){
//					result += "\"" + str + "\",";
//				}
                retStr = retStr + symbol + "(" + result + ")";
            }

        } else if (key.getDataType().equals("Boolean")) {
            retStr = retStr + "==" + (parentItem.getSymbol().equals("1") ? "true" : "false");
        } else {

            String[] sArgs = org.apache.commons.lang3.StringUtils.split(parentItem.getControlValue(), ",");

//			if (controlValues.length == 4) {
//				String temp = retStr;
//				retStr = temp + controlValues[0] + controlValues[1];
//				retStr += " && " + temp + controlValues[2] + controlValues[3];
//			} else if (controlValues.length == 2 && "==".equals(controlValues[0])) {// 只有“==”情况才可能出现数组大小为2
//				retStr += controlValues[0] + controlValues[1];
//			}
            String lowQ = "";
            if (key.getDataType().equals("Date")) {
                lowQ = "\"";
            }
            String temp = retStr;
            if (sArgs != null) {
                if (!StringUtils.isEmpty(sArgs[0]) && sArgs.length == 2 && !StringUtils.isEmpty(sArgs[1])) {
                    retStr = temp + parentItem.getLeftOpt() + lowQ + sArgs[0] + lowQ;
                    retStr += " && " + temp + parentItem.getRightOpt() + lowQ + sArgs[1] + lowQ;
                } else if (!StringUtils.isEmpty(sArgs[0])) {
                    retStr = temp + parentItem.getLeftOpt() + lowQ + sArgs[0] + lowQ;
                } else if (!StringUtils.isEmpty(sArgs[1])) {
                    retStr = temp + parentItem.getRightOpt() + lowQ + sArgs[1] + lowQ;
                }
            }
        }
        ruleNameExtList.add(parentItem.getId());
        if (itemMap.containsKey(parentItem.getPid())) {
            PolicyTreeItem parentNode = itemMap.get(parentItem.getPid());
            String ret = generateDrl(parentNode, itemMap, keyMap, ruleNameExtList);
            if (ret.length() > 0) {
                retStr += ",\n" + ret;
            }
        }
        return retStr;
    }

    /**
     * 获取规则对象
     *
     * @param ruleName  规则名称
     * @param priority  优先级
     * @param factStr   规则变量临时内容
     * @param actionStr 规则结果临时内容
     * @return 规则对象
     */
    private RuleItem getCustomRule(String ruleName, int priority, String factStr, String actionStr) {
        RuleItem rule = new RuleItem();
        rule.setEnabled("on");
        rule.setRuleName(ruleName);
        rule.setSalience(priority);
        DWhen dWhen = new DWhen();
        Fact fact = new Fact();
        fact.setContent(factStr);
        dWhen.setFirstFact(fact);
        DThen dThen = new DThen();
        Action action = new Action();
        action.setContent(actionStr);
        dThen.getListAction().add(action);
        rule.setdWhen(dWhen);
        rule.setdThen(dThen);
        return rule;
    }

    @Override
    public void updateVersion(RuleManage ruleManage) throws BizException {
        // TODO Auto-generated method stub
        this.decisionTreeService.updateVersion(ruleManage);
    }

    @Override
    public void copyRule(RuleManage oldRuleManage, RuleManage ruleManage) throws BizException {
        // TODO Auto-generated method stub
        this.decisionTreeService.copyRule(oldRuleManage, ruleManage);
    }


}
